package com.janlei.tdd.lintcode.t_2423;

import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.function.Predicate;


/**
 * 反射设置私有变量值
 */
public class T_2423 {

    public Student invoke(String name, int age) {
        Student student = new Student();
        // writer your code here
        Predicate<Method> methodPredicate = method -> method.getName().contains("setName");
        Method[] methods = Student.class.getMethods();

        final Method method = Arrays.stream(methods)
                .filter(methodPredicate)
                .findAny()
                .get();

        method.setAccessible(true);

        try {
            method.invoke(student, name);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        student.age = age;

        return student;
    }

}

@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
class Student {
    private String name;
    int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}